#!/usr/bin/python
#-*- coding:utf-8 -*-

import os
import sys
import re

if __name__ == "__main__":
    reload(sys)
    sys.setdefaultencoding('utf8')
    data_file = sys.argv[1]
    datas = open(data_file).read()
    datas = datas.strip(" \s\r")
    read_len = len(datas)
    seg = "\r\n"
    head_e = datas.find("%s%s" % (seg,seg))
    if head_e <= 0:
        seg = "\n"
        head_e = datas.find("%s%s" % (seg,seg))
    if head_e <= 0:
        print "content format err"
        sys.exit()

    len_s = -1
    len_e = -1
    contentlen = -1
    headlen = -1
    if contentlen == -1:
        len_s = datas.find("Content-Length:")
        if len_s < 0:
            len_s = datas.lower().find("content-length:")
        if len_s > 0:
            len_e = datas.find(seg, len_s)
        if len_s > 0 and len_e > 0 and len_e > len_s+15:
            len_str = datas[len_s+15:len_e].strip()
            if len_str.isdigit():
                contentlen = int(datas[len_s+15:len_e].strip())
    headlen = head_e + 2*len(seg)

    if not ((contentlen >= 0 and headlen > 0 and (contentlen + headlen) <= read_len) or \
       (contentlen == -1 and headlen > 0 and headlen <= read_len)):
        print "content format err"
        sys.exit()
    headlist = datas[0:head_e].split(seg)
    first_line = headlist.pop(0)
    command, path, http_version, =  re.split('\s+', first_line)
    headers = {}
    for item in headlist:
        if item.strip() == "":
            continue
        segindex = item.find(":")
        if segindex < 0:
            continue
        key = item[0:segindex].strip()
        value = item[segindex+1:].strip()
        headers[key] = value
    if contentlen > 0:
        body_data = datas[head_e+2*len(seg):] 
        open("./ab_temp.data","w").write(body_data)

    ab_cmd = "ab -c 500 -n 3000 -k "
    for k,v in headers.items():
        if k.lower() == "connection" or k.lower() == "content-length":
            continue
        if k.lower() == "content-type":
            ab_cmd += ' -T "%s"' % v
            continue
        ab_cmd += ' -H "%s: %s"' % (k,v)

    if contentlen > 0:
        ab_cmd += ' -p ab_temp.data'
    ab_cmd += ' "%s"' % path
    print ab_cmd
    print os.popen(ab_cmd).read()
























